/**
 * 招聘需求，新增编辑页
 */
import React from 'react';
import { Form, Card, Button, Input, DatePicker, InputNumber, Select, Radio, message, Spin, Divider } from 'antd';
import { history } from 'umi'
import { get as getPath } from 'object-path';
import moment from 'moment';
import { debounce } from 'lodash';
import { useRequest, defaultFormatResult } from '@/hooks';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import pageTabUtil from '@/utils/pageTabUtil';
import { BottomAction } from '@/components';
import { Organization, Company } from '@/containers';
import { getPostList } from '@/services/Organization/orgmanage';
import { getJobList } from '@/services/organization';
import { dictionaryList } from '@/services/dictionary';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import { FormHeader } from '../components';
import { getOrgCity, getPositionTags, batchSavePositionTags, getRecruitmentInfo, addToHiData } from '../service';
import styles from './index.less';

const { TextArea } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;

const getCity = arr => {
    if (arr && arr.length > 0) {
        const temp = [];
        arr.forEach(item => {
            const area = item?.area || '';
            const tempArr = area.split(',');
            let str = '';
            if (tempArr.length > 3) {
                str = tempArr[2] === '市辖区' ? tempArr[1] : tempArr[2];
            } else if (tempArr.length > 0) {
                str = tempArr[tempArr.length - 1];
            }
            if (!temp.includes(str)) {
                temp.push(str);
            }
        });
        return temp;
    }
    return [];
};

const Apply = ({ form, location }) => {
    const { query } = location;
    const { getFieldDecorator } = form;
    const [loading, setLoading] = React.useState(false);
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [info, setInfo] = React.useState(null);

    const isAddPage = React.useMemo(() => {
        const { pathname = '' } = location;
        return pathname.includes('apply');
    }, [location]);

    // 岗位列表
    const { data: postList, loading: postLoading, run: fetchPostList, mutate: setPostList } = useRequest(
        organizationCode => getPostList({ organizationCode, ...(isAddPage ? { auditStatuses: [2], status: 1 } : {}) }),
        {
            manual: true,
            initialData: [],
            ...defaultFormatResult
        }
    );

    // 职位列表
    const { data: jobList, loading: jobLoading, run: fetchJobList } = useRequest(getJobList, {
        manual: true,
        initialData: [],
        formatResult: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    return data?.rows || [];
                }
                message.error(msg);
            }
            return [];
        }
    });

    // 工作城市
    const { data: cityList, loading: cityLoading, run: fetchCityList, mutate: setCityList } = useRequest(getOrgCity, {
        manual: true,
        initialData: [],
        formatResult: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    return getCity(data);
                }
                message.error(msg);
            }
            return undefined;
        }
    });

    // 获取表单字典
    const { data: dictObj, loading: dictObjLoading } = useRequest(
        () =>
            dictionaryList({
                codes: ['jobNature', 'candidateSexType', 'agreeType', 'timeEmployedType']
            }),
        {
            formatResult: res => {
                if (res) {
                    const { code, data, msg } = res;
                    if (code === 10000) {
                        const obj = {};
                        data.forEach(item => {
                            if (obj[item.code]) {
                                obj[item.code].push(item);
                            } else {
                                obj[item.code] = [item];
                            }
                        });
                        return obj;
                    }
                    message.error(msg);
                }
                return undefined;
            }
        }
    );

    // 获取职位关键词列表
    const { data: tagList, run: fetchPositionTags } = useRequest(tagName => getPositionTags(tagName), {
        // debounceInterval: 400,
        manual: true,
        formatResult: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    return [...new Set(data || [])];
                }
                message.error(msg);
            }
            return undefined;
        }
    });

    const savePositionTags = async tagNameList => {
        const res = await batchSavePositionTags(tagNameList);
        const { code, msg } = res;
        if (code !== 10000) {
            message.error(msg);
        }
    };

    const getDetail = async () => {
        setLoading(true);
        const res = await getRecruitmentInfo(query && query.recruitCode);
        const { data, code, msg } = res;
        if (code === 10000) {
            setInfo(data);
            if (getPath(data, 'organizationCode', '')) {
                fetchPostList(getPath(data, 'organizationCode', ''));
            }
            if (getPath(data, 'companyCode', '')) {
                fetchCityList(getPath(data, 'companyCode', ''));
            }
        } else {
            message.error(msg);
        }
        setLoading(false);
    };

    const handleSubmit = () => {
        form.validateFieldsAndScroll({ scroll: { alignWithTop: true } }, async (err, values) => {
            // console.log('handleSubmit -> values', values);
            if (!err) {
                const { entryDate = [], dutyCode, positionTag, workCity, workNature, ...rest } = values;
                if (positionTag && positionTag.length > 0) {
                    if (positionTag.some(tag => tag.length > 20)) {
                        message.error('单个职位关键词长度不可超过20个字符');
                        return;
                    }
                }
                // 流程不存在提示
                const { workFlowUrl } = await hasWorkFlowByType('Recruit');
                if (!workFlowUrl) {
                    return;
                }

                const tempList = postList.filter(item => item.dutyCode === dutyCode);
                let dutyName = '';
                if (tempList && tempList.length > 0) {
                    dutyName = tempList[0]?.dutyAlias;
                }

                const workNatureList = dictObj?.jobNature;
                let workNatureName = '';
                if (workNatureList && workNatureList.length > 0) {
                    const arrTemp = workNatureList.filter(item => item.dictValue === workNature);
                    if (arrTemp && arrTemp.length > 0) {
                        workNatureName = arrTemp[0].dictName;
                    }
                }

                const params = {
                    ...rest,
                    entryDateStart: entryDate && entryDate.length > 0 ? entryDate[0].format('YYYY-MM-DD') : '',
                    entryDateEnd: entryDate && entryDate.length > 0 ? entryDate[1].format('YYYY-MM-DD') : '',
                    dutyName,
                    dutyCode,
                    workNature,
                    workNatureName,
                    workCity: workCity && workCity.length > 0 ? workCity.join(',') : '',
                    positionTag: positionTag && positionTag.length > 0 ? positionTag.join(',') : '',
                    operationType: 0
                };
                // console.log(params);
                // console.log(JSON.stringify(params));
                setSubmitLoading(true);
                if (positionTag && positionTag.length > 0) {
                    savePositionTags(positionTag);
                }
                if (isAddPage) {
                    addToHiData(params)
                        .then(res => {
                            const { code, msg, data: id } = res;
                            if (code === 10000) {
                                history.push(`${workFlowUrl}${id}`);
                            } else {
                                message.error(msg);
                            }
                        })
                        .finally(() => {
                            setSubmitLoading(false);
                        });
                } else {
                    addToHiData({
                        ...info,
                        ...params,
                        operationType: 1,
                        recruitCode: getPath(query, 'recruitCode', '')
                    })
                        .then(res => {
                            const { code, msg, data: id } = res;
                            if (code === 10000) {
                                history.push(`${workFlowUrl}${id}`);
                            } else {
                                message.error(msg);
                            }
                        })
                        .finally(() => {
                            setSubmitLoading(false);
                        });
                }
            }
        });
    };

    const handleOrgChange = val => {
        form.setFieldsValue({
            dutyCode: undefined
        });
        if (val) {
            fetchPostList(val);
        } else {
            setPostList([]);
        }
    };

    const handleCompanyChange = val => {
        form.setFieldsValue({
            workCity: undefined
        });
        if (val) {
            fetchCityList(val);
        } else {
            setCityList([]);
        }
    };

    const handleDutyChange = val => {
        const desc = postList?.find(item => item.dutyCode === val)?.dutyDesc;
        form.setFieldsValue({
            jobRequirement: desc || ''
        });
    };
    const [initialized, setInitialized] = React.useState(false);
    React.useEffect(() => {
        const dutyCode = query?.dutyCode;
        if (!isAddPage || initialized || !postList?.length || !dutyCode) {
            return;
        }
        handleDutyChange(dutyCode);
        setInitialized(true);
    }, [query?.dutyCode, isAddPage, initialized, setInitialized, JSON.stringify(postList)]);

    React.useEffect(() => {
        form.setFieldsValue({
            workNature: getPath(info, 'workNature', dictObj?.jobNature?.[0]?.dictValue)
        });
    }, [dictObj, info]);

    const handlePositionChange = pCode => {
        const desc = jobList?.find(item => item.positionCode === pCode)?.positionDescription || '';
        form.setFieldsValue({
            positionDesc: desc
        });
    };

    React.useEffect(() => {
        if (!isAddPage) {
            getDetail();
        }
        fetchJobList({ postName: '', pageSize: 99999 });
        fetchPositionTags();
        if (getPath(query, 'organizationCode', '')) {
            fetchPostList(getPath(query, 'organizationCode', ''));
        }
        if (getPath(query, 'companyCode', '')) {
            fetchCityList(getPath(query, 'companyCode', ''));
        }
    }, []);

    const renderOptions = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => (
                <Option value={item.dictValue} key={item.dictValue}>
                    {item.dictName}
                </Option>
            ));
        }
        return null;
    };

    const renderRadios = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => (
                <Radio value={item.dictValue} key={item.dictValue}>
                    {item.dictName}
                </Radio>
            ));
        }
        return null;
    };

    const getEntryDate = () => {
        if (getPath(info, 'entryDateStart', null) && getPath(info, 'entryDateEnd', null)) {
            return [moment(getPath(info, 'entryDateStart', null)), moment(getPath(info, 'entryDateEnd', null))];
        }
        return [];
    };

    const handleTagChange = () => {
        fetchPositionTags('');
    };

    const handleTagSearch = debounce(value => {
        fetchPositionTags(value?.trim() || '');
    }, 400);

    return (
        <PageHeaderWrapper>
            <Card
                title={isAddPage ? '招聘需求申请' : '招聘需求编辑'}
                bordered={false}
                loading={loading}
                extra={
                    <BottomAction>
                        <Button onClick={() => pageTabUtil.goBack()} style={{ marginRight: 8 }}>
                            取消
                        </Button>
                        <Button
                            type="primary"
                            // disabled={
                            //     getPath(info, 'recruitStatus', '') !== '' &&
                            //     getPath(info, 'recruitStatus', '') !== 2 &&
                            //     getPath(info, 'recruitStatus', '') !== 3
                            // }
                            onClick={handleSubmit}
                            loading={submitLoading}
                        >
                            下一步
                        </Button>
                    </BottomAction>
                }
            >
                <FormHeader title="基本信息" />
                <Form className={styles.formWrap}>
                    <Form.Item label="需求部门" className={styles.treeSelectWrap}>
                        {getFieldDecorator('organizationCode', {
                            initialValue: isAddPage
                                ? getPath(query, 'organizationCode', undefined)
                                : getPath(info, 'organizationCode', undefined),
                            rules: [
                                {
                                    required: true,
                                    message: '请选择需求部门'
                                }
                            ]
                        })(
                            <Organization
                                style={{ width: '100%' }}
                                onChange={handleOrgChange}
                                placeholder="请选择需求部门"
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                                disabled={!isAddPage}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="岗位名称">
                        <Spin spinning={postLoading}>
                            {getFieldDecorator('dutyCode', {
                                initialValue: isAddPage
                                    ? getPath(query, 'dutyCode', undefined)
                                    : getPath(info, 'dutyCode', undefined),
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择岗位名称'
                                    }
                                ]
                            })(
                                <Select
                                    style={{ width: '100%' }}
                                    placeholder="请选择岗位名称"
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                    disabled={!isAddPage}
                                    onChange={handleDutyChange}
                                >
                                    {postList?.map(item => (
                                        <Option value={item.dutyCode} key={item.dutyCode}>
                                            {item.dutyAlias}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                    <Form.Item label="需求人数">
                        {getFieldDecorator('recruitNums', {
                            initialValue: getPath(info, 'recruitNums', ''),
                            rules: [
                                {
                                    required: true,
                                    message: '请输入需求人数'
                                }
                            ]
                        })(
                            <InputNumber
                                min={0}
                                max={999}
                                precision={0}
                                placeholder="请输入需求人数"
                                style={{ width: '100%' }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="行政机构">
                        {getFieldDecorator('companyCode', {
                            initialValue: getPath(info, 'companyCode', undefined),
                            rules: [
                                {
                                    required: true,
                                    message: '请选择行政机构'
                                }
                            ]
                        })(
                            <Company
                                style={{ width: '100%' }}
                                placeholder="请选择行政机构"
                                onChange={handleCompanyChange}
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                                disabled={!isAddPage}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="工作城市">
                        <Spin spinning={cityLoading}>
                            {getFieldDecorator('workCity', {
                                initialValue: getPath(info, 'workCity', undefined)
                                    ? getPath(info, 'workCity', '').split(',')
                                    : undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择工作城市'
                                    }
                                ]
                            })(
                                <Select
                                    mode="multiple"
                                    style={{ width: '100%' }}
                                    placeholder="请选择工作城市"
                                    allowClear
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                >
                                    {cityList?.map(item => (
                                        <Option value={item} key={item}>
                                            {item}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                    <Form.Item label="工作性质">
                        <Spin spinning={dictObjLoading}>
                            {getFieldDecorator('workNature', {
                                initialValue: getPath(info, 'workNature', dictObj?.jobNature?.[0]?.dictValue)
                            })(<Radio.Group>{renderRadios(dictObj?.jobNature)}</Radio.Group>)}
                        </Spin>
                    </Form.Item>
                    <Form.Item label="到岗时间">
                        {getFieldDecorator('entryDate', {
                            initialValue: getEntryDate()
                        })(
                            <RangePicker
                                style={{ width: '100%' }}
                                getCalendarContainer={trigger => trigger.parentElement}
                            />
                        )}
                    </Form.Item>
                </Form>
                <Divider />
                <FormHeader title="职位要求" />
                <Form className={styles.formWrap}>
                    <Form.Item label="经验和学历" style={{ marginBottom: 0 }} required>
                        <div style={{ display: 'flex' }}>
                            <Form.Item label="" colon={false} style={{ width: '50%', marginRight: 8 }}>
                                <Spin spinning={dictObjLoading}>
                                    {getFieldDecorator('workYears', {
                                        initialValue: getPath(info, 'workYears', undefined),
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择工作年限'
                                            }
                                        ]
                                    })(
                                        <Select
                                            placeholder="请选择工作年限"
                                            allowClear
                                            getPopupContainer={triggerNode => triggerNode.parentElement}
                                        >
                                            {renderOptions(dictObj?.timeEmployedType)}
                                        </Select>
                                    )}
                                </Spin>
                            </Form.Item>
                            <Form.Item label="" colon={false} style={{ width: '50%' }}>
                                <Spin spinning={dictObjLoading}>
                                    {getFieldDecorator('recruitDegree', {
                                        initialValue: getPath(info, 'recruitDegree', undefined),
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择学历'
                                            }
                                        ]
                                    })(
                                        <Select
                                            placeholder="请选择学历"
                                            allowClear
                                            getPopupContainer={triggerNode => triggerNode.parentElement}
                                        >
                                            {renderOptions(dictObj?.agreeType)}
                                        </Select>
                                    )}
                                </Spin>
                            </Form.Item>
                        </div>
                    </Form.Item>
                    <Form.Item label="性别">
                        <Spin spinning={dictObjLoading}>
                            {getFieldDecorator('recruitSex', { initialValue: getPath(info, 'recruitSex', '3') })(
                                <Radio.Group>{renderRadios(dictObj?.candidateSexType)}</Radio.Group>
                            )}
                        </Spin>
                    </Form.Item>
                    <Form.Item label="匹配职位">
                        <Spin spinning={jobLoading}>
                            {getFieldDecorator('positionCode', {
                                initialValue: getPath(info, 'positionCode', undefined),
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择匹配职位'
                                    }
                                ]
                            })(
                                <Select
                                    placeholder="请选择匹配职位"
                                    allowClear
                                    showSearch
                                    optionFilterProp="label"
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                    onChange={handlePositionChange}
                                >
                                    {jobList?.map(item => (
                                        <Option
                                            value={item.positionCode}
                                            key={item.positionCode}
                                            label={item.positionName}
                                        >
                                            {item.positionName}
                                            {item.rankValue ? '/' : ''}
                                            {item.rankValue}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                    <Form.Item label="职位要求">
                        {getFieldDecorator('positionDesc', {
                            initialValue: getPath(info, 'positionDesc', ''),
                            rules: [
                                {
                                    required: true,
                                    whiteSpace: true,
                                    message: '请输入职位要求'
                                }
                            ]
                        })(
                            <TextArea
                                placeholder="请输入职位要求"
                                autoSize={{ minRows: 3, maxRows: 6 }}
                                maxLength={800}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="岗位职责">
                        {getFieldDecorator('jobRequirement', {
                            initialValue: getPath(info, 'jobRequirement', '')
                        })(
                            <TextArea
                                placeholder="请输入岗位职责"
                                autoSize={{ minRows: 3, maxRows: 6 }}
                                maxLength={2000}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="职位关键词">
                        {getFieldDecorator('positionTag', {
                            initialValue: getPath(info, 'positionTag', '')
                                ? getPath(info, 'positionTag', '').split(',')
                                : undefined
                        })(
                            <Select
                                mode="tags"
                                style={{ width: '100%' }}
                                placeholder="请选择职位关键词"
                                allowClear
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                                onFocus={handleTagChange}
                                onSearch={handleTagSearch}
                                tokenSeparators={[',']}
                                filterOption={false}
                            >
                                {tagList?.map(item => (
                                    <Option value={item} key={item}>
                                        {item}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                </Form>
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create({})(Apply);
